package com.cuit.zuke.system.oauth2;


import com.cuit.zuke.system.entity.SysAdminEntity;
import com.cuit.zuke.system.entity.SysAdminTokenEntity;
import com.cuit.zuke.system.service.SysAdminService;
import com.cuit.zuke.system.service.SysAdminTokenService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @program: zuke
 * @description: 自定义Realm
 * @author: KamTang
 * @create: 2022-04-07 09:57
 **/
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private SysAdminTokenService sysAdminTokenService;

    @Autowired
    private SysAdminService adminService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof Oauth2Token;
    }

    /**
     * 授权
     * @param principalCollection
     * @return AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysAdminEntity admin = (SysAdminEntity) principalCollection.getPrimaryPrincipal();
        Long userId = admin.getUserId();

        // 用户权限列表
        Set<String> permissions = adminService.getUserPermissions(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 认证
     * @param authenticationToken token
     * @return AuthenticationInfo
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取token
        String token = (String) authenticationToken.getPrincipal();
        SysAdminTokenEntity tokenEntity = sysAdminTokenService.queryByToken(token);
        // 获取的tokenEntity失效
        if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
            throw new IncorrectCredentialsException("token已失效，请重新登录。");
        }
        // 根据id查询admin
        SysAdminEntity admin = adminService.getById(tokenEntity.getUserId());
        // 是否锁定
        if (admin.getStatus() == 0) {
            throw new LockedAccountException("该账号已被锁定，请联系管理员。");
        }
        return new SimpleAuthenticationInfo(admin, token, getName());
    }
}
